package com.huawei.aiosproj.utils;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GUIResult {

    private static final String TAG = "GUIResult";

    public static ActionResult parseActionResponse(String jsonResponse) {
        try {
            JSONObject root = new JSONObject(jsonResponse);
            JSONArray choices = root.getJSONArray("choices");
            JSONObject choice = choices.getJSONObject(0);
            JSONObject message = choice.getJSONObject("message");
            String content = message.getString("content");

            // 提取Action行
            String actionLine = extractActionLine(content);
            if (actionLine == null) {
                Log.e(TAG, "No valid action line found in content");
                return null;
            }

            return parseAction(actionLine);
        } catch (JSONException e) {
            Log.e(TAG, "JSON parsing error: " + e.getMessage());
            return null;
        }
    }

    public static String extractActionLine(String content) {
        String[] lines = content.split("\\r?\\n");
        for (String line : lines) {
            if (line.startsWith("Action: ")) {
                return line.substring(8); // 移除"Action: "前缀
            }
        }
        return null;
    }

    public static ActionResult parseAction(String actionStr) {
        // 匹配动作类型和括号内的参数
        Pattern actionPattern = Pattern.compile("^(\\w+)\\((.*)\\)$");
        Matcher matcher = actionPattern.matcher(actionStr.trim());

        if (!matcher.find()) {
            Log.e(TAG, "Invalid action format: " + actionStr);
            return null;
        }

        String actionType = matcher.group(1);
        String paramsStr = matcher.group(2);
        Map<String, String> params = parseParams(actionType, paramsStr);

        return new ActionResult(actionType, params);
    }

    public static Map<String, String> parseParams(String actionType, String paramsStr) {
        Map<String, String> params = new HashMap<>();

        try {
            switch (actionType) {
                case "click":
                case "long_press":
                    Log.e(TAG, "parseParams: " + "处理click 和 long press 参数解析");
                    extractPointParam(paramsStr, "point", params);
                    break;

                case "type":
                    extractContentParam(paramsStr, params);
                    break;

                case "scroll":
                    extractScrollParams(paramsStr, params);
                    break;

                case "open_app":
                    extractAppNameParam(paramsStr, params);
                    break;

                case "drag":
                    extractDragParams(paramsStr, params);
                    break;

                case "press_home":
                case "press_back":
                    // 无参数
                    break;

                case "finished":
                    extractFinishedContent(paramsStr, params);
                    break;

                default:
                    Log.e(TAG, "Unknown action type: " + actionType);
            }
        } catch (Exception e) {
            Log.e(TAG, "Param parsing error: " + e.getMessage());
        }

        return params;
    }

    // 辅助方法：解析坐标点参数
    private static void extractPointParam(String input, String paramName, Map<String, String> params) {
        Pattern pattern = Pattern.compile(paramName + "='<point>(\\d+)\\s+(\\d+)</point>'");
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            params.put(paramName, matcher.group(1) + " " + matcher.group(2));
        } else {
            throw new RuntimeException("Invalid point format in: " + input);
        }
    }

    // 辅助方法：解析文本内容参数
    private static void extractContentParam(String input, Map<String, String> params) {
        Pattern pattern = Pattern.compile("content='(.*?)'");
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            params.put("content", matcher.group(1).replace("\\n", "\n"));
        } else {
            throw new RuntimeException("Invalid content format in: " + input);
        }
    }

    // 辅助方法：解析滚动参数
    private static void extractScrollParams(String input, Map<String, String> params) {
        String[] parts = input.split(",\\s*");
        if (parts.length != 2) throw new RuntimeException("Invalid scroll params: " + input);

        extractPointParam(parts[0], "point", params);

        Pattern dirPattern = Pattern.compile("direction='(\\w+)'");
        Matcher dirMatcher = dirPattern.matcher(parts[1]);
        if (dirMatcher.find()) {
            params.put("direction", dirMatcher.group(1));
        } else {
            throw new RuntimeException("Invalid direction in: " + input);
        }
    }

    // 辅助方法：解析应用名称参数
    private static void extractAppNameParam(String input, Map<String, String> params) {
        Pattern pattern = Pattern.compile("app_name='(.*?)'");
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            params.put("app_name", matcher.group(1));
        } else {
            throw new RuntimeException("Invalid app name format: " + input);
        }
    }

    // 辅助方法：解析拖拽参数
    private static void extractDragParams(String input, Map<String, String> params) {
        String[] parts = input.split(",\\s*");
        if (parts.length != 2) throw new RuntimeException("Invalid drag params: " + input);

        extractPointParam(parts[0], "start_point", params);
        extractPointParam(parts[1], "end_point", params);
    }

    // 辅助方法：解析完成消息
    private static void extractFinishedContent(String input, Map<String, String> params) {
        Pattern pattern = Pattern.compile("content='(.*?)'");
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            params.put("content", matcher.group(1));
        } else {
            throw new RuntimeException("Invalid finished content: " + input);
        }
    }

    // 结果封装类
    public static class ActionResult {
        private final String action;
        private final Map<String, String> params;

        public ActionResult(String action, Map<String, String> params) {
            this.action = action;
            this.params = params;
        }

        public String getAction() {
            return action;
        }

        public Map<String, String> getParams() {
            return params;
        }
    }
}
